﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

namespace Sern.Common
{
    public static class ServiceHostHelper
    {
        public static void EnableMex(this ServiceHost host)
        {
            var metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(metadataBehavior);
            }   
        }

        public static void ConfigureAsSingleton(this ServiceHost host)
        {
            var defaultServiceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
            defaultServiceBehavior.InstanceContextMode = InstanceContextMode.Single;
        }

        public static ServiceEndpoint CreateMsmqIfNostExists(this ServiceEndpoint serviceEndpoint)
        {
            var path = serviceEndpoint.ListenUri.PathAndQuery.Replace(@"/private/",@".\private$\");
            //path = path.ToLower().Replace("net.msmq://", "DIRECT=http://").Replace("/private/", "/msmq/private$/");
            if (!MessageQueue.Exists(path))
            {
                var msmq = MessageQueue.Create(path,true);
            }
            return serviceEndpoint;
        }

        public static ServiceEndpoint DeleteMsmqIfExists(this ServiceEndpoint serviceEndpoint)
        {
            var path = serviceEndpoint.ListenUri.PathAndQuery.Replace(@"/private/",@".\private$\");;
            //path = path.ToLower().Replace("net.msmq://", "DIRECT=http://").Replace("/private/", "/msmq/private$/");
            if (MessageQueue.Exists(path))
                MessageQueue.Delete(path);
            return serviceEndpoint;
        }
    }
}
